layui.define(function (exports) {

    var json;
    var file_up;
    var accessid = '';
    var accesskey = '';
    var host = '';
    var policyBase64 = '';
    var signature = '';
    var callbackbody = '';
    var filename = ''
    var key = '';
    var expire = 0;
    var g_object_name = '';
    var g_object_name_type = '';
    var index;
    var send_request = function (ori_filename) {
        var xmlhttp = null;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        if (xmlhttp != null) {
            serverUrl = json.url
            xmlhttp.open("GET", serverUrl + "&ori_filename=" + ori_filename, false);
            xmlhttp.send(null);
            return xmlhttp.responseText
        }
        else {
            alert("Your browser does not support XMLHTTP.");
        }
    };

    var check_object_radio = function () {

        g_object_name_type = json.theform;

    }

    var get_signature = function (ori_filename) {
        body = send_request(ori_filename)
        var obj = eval("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        //expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
    };


    var set_upload_param = function (up, filename) {

        get_signature(filename);
        g_object_name = key;
        new_multipart_params = {
            'key': g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': callbackbody,
            'signature': signature,
        };
        up.setOption({
            'url': host,
            'multipart_params': new_multipart_params
        });

        up.start();
    }


    //外部接口
    var upload = {
        config: {} //全局配置项

        //设置全局项
        , set: function (options) {
            var that = this;
            that.config = $.extend({}, that.config, options);
            return that;
        }

        //事件监听
        , on: function (events, callback) {
            return layui.onevent.call(this, MOD_NAME, events, callback);
        }
    }
    //操作当前实例
    var thisUpload = function () {
        var that = this;
        return {
            upload: function (files) {
                that.upload.call(that, files);
            }
            , config: that.config
        }
    }

    //构造器
    Class = function (options) {
        var that = this;
        that.config = $.extend({}, that.config, upload.config, options);
        that.render();
    };

    //默认配置
    Class.prototype.config = {
        select_id: 'selectfiles',
        file_number: 10,
        star_id: 'postfiles ',
        url: "/oss/getSignature?dir=zy/", //默认url
        file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z",
        size: "100mb",
        theform: "local_name",//local_name random_name，
        img_box: "imgBox",
        done: function (res, infor) {
            //上传完毕回调
        },
        error: function () {
            //请求异常回调
        }
    };

    //初始渲染
    Class.prototype.render = function (options) {
        var that = this;
        options = that.config;
        json = options;
        //that.file();
        //that.events();
        that.uploader_file(options);

    };

    Class.prototype.uploader_file = function (options) {
        var uploader = new plupload.Uploader({

            runtimes: 'html5,flash,silverlight,html4',
            browse_button: options.select_id,
            //multi_selection: false,
            container: document.getElementById('container'),
            flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
            silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
            url: 'http://oss.aliyuncs.com',

            filters: {
                mime_types: [ //只允许上传图片和zip,rar文件
                    {title: "*", extensions: options.file_type}
                ],
                max_file_size: options.size, //最大只能上传10mb的文件
                prevent_duplicates: true //不允许选取重复文件
            },

            init: {
                PostInit: function () {//console.log("初始化")
                    $("#" + options.star_id).click(function () {
                        if (uploader.total.queued > 0) {
                            index = layer.load(3);
                            setTimeout(function(){set_upload_param(uploader, '');},10);
                        }

                    });
                },

                FilesAdded: function (up, files) {//console.log("文件添加")

                    plupload.each(files, function (file) {
                        if ( $('.box_con').length + 1 >options.file_number){
                            uploader.removeFile(uploader.getFile(file.id));//删除文件
                            Common.info("最多上传" +options.file_number +"个附件!");
                            return;
                        }
                        var str = '<div class="box_con" id="' + file.id + '" style="width: 200px; height: 100px;line-height: 28px; margin-right: 5px;float: left; ">';
                        str += '<p style="width: 100%; overflow: hidden;text-overflow: ellipsis;white-space: nowrap;"><a href="javascript:" style="float: left;" class="file-operate layui-btn layui-btn-xs layui-btn-danger" file_id="' + file.id + '"><i class="layui-icon">&#xe640;</i></a>' + file.name + '</p>';
                        str += '</div>';
                        $("#" + options.img_box).append(str);
                    });
                },


                BeforeUpload: function (up, file) {//console.log("文件上传前")
                    set_upload_param(up, file.name);

                },

                UploadProgress: function (up, file) {//console.log("上传进行中");

                    $("#" + file.id).find('span i').text(file.percent + "%");
                    $("#" + file.id).find(".progBar").css("width", file.percent + "%");

                },

                FileUploaded: function (up, file, info) {//console.log("上传成功")
                    //关闭遮罩
                    layer.close(index);
                    options.done(file, info)
                },

                Error: function (up, err) {
                    layer.close(index);
                    var msg = '';
                    switch (err.code) {
                        case -601:
                            msg = '您选择的文件类型不匹配，支持文件：jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z';
                            break;
                        case -602:
                            msg = '您选择文件已经在上传列表中了！';
                            break;
                        case -600:
                            msg = '文件太大';
                            break;
                        default :
                            msg = "\nError xml:" + err.response;
                            break;

                    }
                    Common.info(msg);
                }
            }


        })

        uploader.init();
        $(document).on("click", ".file-operate", function () {
            var file_id = $(this).attr("file_id");
            if(uploader.getFile(file_id)){
                uploader.removeFile(uploader.getFile(file_id));//删除文件
            }
            $(this).parents('.box_con').remove();
        })

    }

    //核心入口
    upload.render = function (options) {
        var inst = new Class(options);
        return thisUpload.call(inst);
    };


    exports('uploadOss', upload);
});